package com.ag.oa.shiro;

import com.ag.oa.core.entity.po.SysUserPO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * 加密工具类
 */
public class ShiroUtil {

    public final static int hashIterations = 16;  // 循环次数
    public final static String hashAlgorithmName = "SHA-256";  // 加密算法

    public static String sha256(String password, String salt) {

        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }

    /**
     * 获取 shiro session
     */
    public static Session getSession() {

        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 获取 shiro subject
     */
    public static Subject getSubject() {

        return SecurityUtils.getSubject();
    }

    /**
     * 获取 shiro 中的真正主体
     */
    public static SysUserPO getUserEntity() {

        return (SysUserPO) SecurityUtils.getSubject().getPrincipal();
    }

    public static Integer getUserId() {

        return getUserEntity().getUserId();
    }

    public static void setSessionAttribute(Object key, Object value) {

        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {

        return getSession().getAttribute(key);
    }

    public  static  boolean isLogin() {

        return SecurityUtils.getSubject().getPrincipal()!=null;
    }

    public static void logout() {

        SecurityUtils.getSubject().logout();
    }

}
